package de.koo.grum.test.integration

import de.koo.grum.domain.Address;
import de.koo.grum.domain.User;
import grails.test.*

class UserTests extends GrailsUnitTestCase {
    def newIds

    protected void setUp() {
        super.setUp()

        newIds=[];

        def user = new User(username:"bsimpson",password:"secret",firstname:"Bart",lastname:"Simpson")
        Address address = new Address(city:"Springfield",street:"strasse 1",zipcode:"10001")
        user.address=address

        address.save(flush:true)
        user.save(flush:true)

        newIds <<= user.id
    }

    protected void tearDown() {
        super.tearDown()

        newIds.each() { newId ->
            def user=User.get(newId)
            if (user!=null) {
                def address=user.address
                address.delete(flush:true)
                user.delete(flush:true)
            }
        }
    }

    void testShow() {
        def user=User.findByUsername("bsimpson")

        assert user != null
        assert user.username=="bsimpson"
    }

    void testList() {
        assert User.list().size() > 0
    }

    void testSearch() {
        def searchString="bsi"

        def c = User.createCriteria()
        def users = c {
            or { like("firstname","%${searchString}%")
                like("lastname","%${searchString}%")
                like("username","%${searchString}%")
            }
        }

        assert users.size() > 0
    }

    void testCreate() {
        def user = new User(username:"hsimpson",password:"secret",firstname:"Homer",lastname:"Simpson")
        Address address = new Address(city:"Springfield",street:"strasse 2",zipcode:"10002")

        user.address=address

        if(address.validate() && user.validate()) {
            address.save(flush:true)
            user.save(flush:true)

            newIds <<= user.id
        }
        else {
            assert user.errors.allErrors.size() > 0
            user.errors.allErrors.each {log.error(it)}
        }

        assert User.get(user.id)!=null
        assert newIds.size()==2
    }

    void testUpdate() {
        def user=User.findByUsername("bsimpson")
        assert user!=null

        def id=user.id
        def address = null

        if(user) {
            user.firstname="Lisa"

            if (user.address) {
                address = Address.get(user.address.id)
                address.city = "Frankfurt"

                user.address=address
            }

            if(address.validate() && user.validate()) {
                address.save(flush:true)
                user.save(flush:true)
            }
            else {
                assert user.errors.allErrors.size() > 0
                user.errors.allErrors.each {log.error(it)}
            }
        }

        assert User.get(id)!=null
        assert user.firstname=="Lisa"
        assert user.address.city=="Frankfurt"
    }

    void testDelete() {
        //tested in tearDown
    }


}
